package com.wgzx.modbus.handler;

import com.wgzx.modbus.entity.ModbusRspFrame;
import com.wgzx.modbus.message.MsgManager;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ChannelHandler.Sharable
public class ModbusResponseHandler extends SimpleChannelInboundHandler<ModbusRspFrame> {

    private MsgManager msgManager;

    public ModbusResponseHandler(MsgManager msgManager) {
        this.msgManager = msgManager;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ModbusRspFrame msg) {
        int transactionId = msg.getHeader().getTransactionIdentifier();
        this.msgManager.responseArrive(transactionId, msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("modbus channel error", cause);
        ctx.channel().close();
    }
}
